#!/bin/bash

# This script aim to create a virtual python env
# for air-gapped environment which doesn't have
# docker running.

# Set runtime variables
PYTHON_VERSION=${PYTHON_VERSION:-3.6.8}

PYTHON_DOWNLOAD_URL=${PYTHON_DOWNLOAD_URL:-https://www.python.org/ftp/python/$PYTHON_VERSION/Python-$PYTHON_VERSION.tar.xz}

PYTHON_HOME_PATH=${PYTHON_HOME_PATH:-$HOME/.local/python-$PYTHON_VERSION}

PYTHON_DEFAULT_MODULES="netaddr pyyaml jmespath ansible pywinrm passlib requests docker cryptography pyOpenSSL elasticsearch elasticsearch-curator bs4"

if [[ -z $PYTHON_MODULES ]]; then
    PYTHON_MODULES=$PYTHON_DEFAULT_MODULES
fi

# Download python
if [ ! -f /tmp/Python-$PYTHON_VERSION.tar.xz ]; then
    mkdir -p /tmp/
    cd /tmp/
    wget $PYTHON_DOWNLOAD_URL -O /tmp/Python-$PYTHON_VERSION.tar.xz
fi

# Download and install python
if [ ! -f $PYTHON_HOME_PATH/bin/python ]; then
    mkdir -p /mnt/ramdisk
    mount -t tmpfs -o size=2G tmpfs /mnt/ramdisk
    cp /tmp/Python-$PYTHON_VERSION.tar.xz /mnt/ramdisk/Python-$PYTHON_VERSION.tar.xz
    cd /mnt/ramdisk
    tar -xf Python-$PYTHON_VERSION.tar.xz
    cd Python-$PYTHON_VERSION
    ./configure \
      --prefix=$PYTHON_HOME_PATH \
#      --enable-optimizations \
      --disable-debug \
      --with-ensurepip
    make -j
    make install
    make clean
fi

# Set environment variables
export PATH=$PYTHON_HOME_PATH/bin:$PATH
export PYTHONHOME=$PYTHON_HOME_PATH

if [ ! -f $PYTHONHOME/bin/ansible ]; then
  $PYTHONHOME/bin/python3 -m pip install --no-cache-dir --upgrade pip
  $PYTHONHOME/bin/python3 -m pip install --no-cache-dir $PYTHON_MODULES
  # Check if ansible is installed
  which ansible
  ansible --version
fi
